<template>
  <view class="page-container">
    <!--  轮播  -->
    <view class="swiper-container">
      <wd-swiper
          :list="providerInfoObj.pictures"
          :indicator="false"
          custom-image-class="custom-image"
          autoplay
          value-key="imageUrl"
          height="222"
      ></wd-swiper>
    </view>
    <!--  景区名称、等级  -->
    <view class="scenic-spot-name-container">
      <view class="scenic-spot-name">{{providerInfoObj.name}}</view>
      <view class="scenic-spot-level">{{providerInfoObj.grade}}A级景区</view>
    </view>
    <!--  景区营业状态和营业时间  -->
    <view class="business-status-container">
      <text class="business-status">{{providerStatus(providerInfoObj.businessStatus)}}</text>
      <text class="business-time">{{providerInfoObj.openingHours}}</text>
    </view>
    <!--  景区地址以及联系方式 -->
    <view class="address-contact-container">
      <view class="address-container">{{providerInfoObj.address}}</view>
      <view class="map-contact-container">
        <view class="map-container" @click="handleOpenLocation">
          <wd-icon name="location" size="18px" color="#1b9c61"></wd-icon>
          <text>地图</text>
        </view>
        <view class="map-container" @click="handleCallPhone">
          <wd-icon name="call" size="18px" color="#1b9c61"></wd-icon>
          <text>电话</text>
        </view>
      </view>
    </view>
    <!-- 公告   -->
    <view class="notice-container" v-if="providerInfoObj.warn">
      <wd-notice-bar
          color="#181818"
          background-color="#ffffff"
          custom-class="custom-notice-bar"
      >
        <template #prefix>
          <view class="flex flex-center">
            <image class="notice-img" src="http://img.jowong.com/aba/2025-03-24/公告_1742798545874.png" ></image>
            <text class="ml10 mr10">公告：</text>
          </view>
        </template>
        <!--        淡季入园政策 | 游玩须知-->
        {{providerInfoObj.warn}}
        <template #suffix>
          <wd-icon name="arrow-right" size="18px" color="#aa5414"></wd-icon>
        </template>
      </wd-notice-bar>
    </view>
    <!--  内容切换  -->
	<wd-sticky :offset-top="0">
		<view style="width: 100vw;background-color: #fff;">
			
			<view class="switch-container">
			  <view
				  v-for="(item,index) in choiceSwitchList"
				  :key="index"
				  :class="[index === choiceSwitchIndex ? 'selected-choice-radio' : '','choice-radio']"
				  @click="setSwitch(index)"
			  >{{item}}</view>
			</view>
			
			<!--  日期选择  -->
			<view class="date-container" v-if="choiceSwitchIndex === 0">
			  <ChooseDate
				  :initialDate="initialDate"
				  :minDate="minDate"
				  :maxDate="maxDate"
				  :choiceDate="startDate"
				  @confirmDate="handleConfirmDate"
			  ></ChooseDate>
			</view>
			<!--  商品分类枚举  -->
			<view class="category-list-container" v-else>
			  <view  v-for="(item,index) in labelProductList" :key="item.id"
				:class="['category-item mr20',index === choicearoundIndex ? 'selectedradio' : '',]" 
				@click="setAround(item,index)">{{item.name}}
			  </view> 
			</view>
		</view>
	</wd-sticky>
    <!--  周边产品列表  -->
    <view class="around-product-list" v-if="choiceSwitchIndex === 1">
      <view class="around-product-item mt30" v-for="(around) in aroundList" :key="around.id">
        <view class="img-container">
          <image class="img" :src="around.content.headImageUrl" lazy-load/>
          <view class="distant-container" v-if="around.content.distance">
            <wd-icon name="location" size="16px" color="#fffff"></wd-icon>
            <text class="ml10">{{convertToKilometers(around.content.distance)}}</text>
          </view>
        </view>
        <view class="product-name">{{around.content.name}}</view>
        <view class="category-item-list">{{around.content.address}}
          <!-- 演出 I 场馆展出 -->
        </view>
      </view>
	  <wd-status-tip v-if="aroundList.length == 0" image="search" tip="当前搜索无结果" />
    </view>
    <!-- 侧边栏 + 内容区 -->
    <view class="wraper" v-else>
	<wd-sticky :offset-top="130" custom-style="z-index: -1;">
      <wd-sidebar v-model="active" @change="handleChange"  custom-style="width: 140rpx;z-index:-1">
        <wd-sidebar-item
            v-for="(item, index) in labelProductList"
            :key="index"
            :value="index"
            :label="item.name"
            :custom-style="{
              background: active === index ? '#1b9c61' : '#ffffff',
              borderTopRightRadius: '10rpx',
              borderBottomRightRadius: '10rpx',
              color: active === index ? '#ffffff' : '#333',
              padding:'26rpx 0',
              textAlign:'center',
              fontSize: '22rpx'
            }"
        />
      </wd-sidebar>
	</wd-sticky>
	  
      <scroll-view class="content">
        <view v-for="(item, index) in labelProductList" :key="index" class="category" style="margin-bottom: 30rpx;" >
          <view class="mb20">{{item.name}}</view>
          <view class="product-list" >
            <view
                class="mb20 product-item"
                v-for="(cell, cellIndex) in item.itemContent"
                :key="index" @click="reservationProduct(cell,index,0)"
            >
              <view class="product-name">{{cell.content.name}}</view>
              <view class="product-use-rule">票预约购票实行实名制，预订成功后凭有效证件入园，无需换</view>
              <view class="product-introduction-price-sale-btn flex">
                <view class="product-introduction">官方 I 随买随用 I 有条件退 I  无需取票</view>
                <view class="sale-price">{{cell.price}}</view>
                <view class="sale-btn" @click="reservationProduct(cell,index,1)">选购</view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
  import {onLoad} from "@dcloudio/uni-app";
  import { ref,onMounted,nextTick, reactive } from 'vue';
  import {useMixin} from "@/hook/useMixin";
  import ChooseDate from "@/ticketSubPack/components/dateCalendar/index.vue";
  import dayjs from "dayjs";

  const {providerStatus} = useMixin();


  import {getRect,isArray} from "wot-design-uni/components/common/util";
  import {providerInfoDetail} from "@/api/common";
  import {guideLabelList} from "@/api/system";
  import {productMiniPrice} from "@/api/ticket";
  import {start} from "node:repl";


  const choiceSwitchIndex = ref(0);
  const choicearoundIndex = ref(0);
  const choiceSwitchList = ref(["预定","周边"]);
  const minDate = ref("");
  const maxDate = ref("");
  const startDate = ref("");
  const initialDate = ref("");
  const providerId = ref(null);
  const providerInfoObj = ref({});
  const labelProductList = ref([]);

  const active = ref(0)
  const scrollTop = ref(0)
  const itemScrollTop = ref([])
  function handleChange({ value }) {
    active.value = value
    scrollTop.value = itemScrollTop.value[value] - 840
  }
  function onScroll(e) {
    const {scrollTop} = e.detail
    // console.log(itemScrollTop.value,'scrollTop')
    const threshold = 50 // 下一个标题与顶部的距离
    if (scrollTop < threshold) {
      active.value = 0
      return
    }
    // const index = itemScrollTop.value.findIndex((top) => top > scrollTop && top - scrollTop <= threshold)
    const index = itemScrollTop.value.findIndex((top) => top > scrollTop - 200)
    if (index > -1) {
      active.value = index
    }
  }
  const reservationProduct = (item,index,type) => {
    // console.log(item,'item');
    let {content:{id:productId,name,merchantId}} = item;
    labelProductList.value[index].choosed = true;
    uni.navigateTo({
      url:`/ticketSubPack/pages/ticketDetail/index?startDate=${startDate.value}&providerId=${providerId.value}&productId=${productId}&productName=${name}&type=${type}`
    })
  };
  const handleOpenLocation = () => {
    uni.openLocation({
      latitude: providerInfoObj.value.lat,
      longitude: providerInfoObj.value.lnt,
      name: providerInfoObj.value.name,
    })
  };
	function convertToKilometers(meters) { 
	  let kilometers = meters / 1000;
	  if(kilometers == 0) return null; 
	  if(kilometers != 0) return '距离我'+kilometers.toFixed(1)+'km'; 
	}
  const handleCallPhone = () => {
    uni.makePhoneCall({
      phoneNumber: providerInfoObj.value.contactMobile
    })
  };
  const queryProviderInfo = async () => {
    await providerInfoDetail({id:providerId.value}).then(res => {
      let { maxPreBook,minPreBook } = res.result;
      initialDate.value = dayjs().add(minPreBook,'day').format("YYYY-MM-DD");
      startDate.value = dayjs().add(minPreBook,'day').format("YYYY-MM-DD");
      minDate.value = dayjs().add(minPreBook,'day').format("YYYY-MM-DD");
      maxDate.value = dayjs().add(maxPreBook,'day').format("YYYY-MM-DD");
      providerInfoObj.value = res.result;
	  providerInfoObj.value.pictures = providerInfoObj.value.pictures.map(item => item.imgUrl)
	  const exists = providerInfoObj.value.pictures.some(item => item === providerInfoObj.value.headImageUrl);
	  if(!exists) {
		  providerInfoObj.value.pictures.push(providerInfoObj.value.headImageUrl)
	  } 
    });
  };
  const queryGuideLabelList = async () => {
    await guideLabelList({id:providerId.value,tagType:choiceSwitchIndex.value,playDate: startDate.value}).then(res => {
      labelProductList.value = res.result;
      console.log(labelProductList,'labelProductList');
    });
  };
  const queryProductMiniPriceList = async () => {
    let idObjList = [];
    labelProductList.value.forEach((outsideItem,outsideIndex) => {
      /* 判断只有 id 为5 才去查询时因为现在只有 id 为5的服务商，其他都是 mock 数据 */
      if(outsideItem.itemContent && outsideItem.itemContent.length) {
        outsideItem.itemContent.forEach((item,innerIndex) => {
          idObjList.push({id:item.content.id,outsideIndex,innerIndex});
        });
      }
    });
    let idList = idObjList.map(item => item.id);
    await productMiniPrice({ids:idList}).then(res => {
      let {result} = res;
      if(result && result.length) {
        result.forEach((priceItem) => {
          idObjList.forEach(idObjItem => {
            if(priceItem.id === idObjItem.id) {
              labelProductList.value[idObjItem.outsideIndex].itemContent[idObjItem.innerIndex].price = priceItem.price;
            }
          });
        })
      }
    });
  };
  const handleConfirmDate = async (event) => {
    let {date} = event;
    startDate.value = date;
    active.value = 0;
    scrollTop.value = 0;
    await queryGuideLabelList();
    await queryProductMiniPriceList();
  };
  const setSwitch = (index)=>{ 
	  choiceSwitchIndex.value = index
	  queryGuideLabelList()
  } 
  const aroundList = ref([]) 
  const setAround = (val,index)=>{
	  console.log(val,index);
	  aroundList.value = val.itemContent
	  choicearoundIndex.value = index
  } 
  onLoad((options) => {
    let {id,name} = options;
    providerId.value = id; 
    uni.setNavigationBarTitle({title:name});
  }); 
  onMounted(async() => {
    await queryProviderInfo(); 
    await queryGuideLabelList();
    await queryProductMiniPriceList();
    nextTick(() => {
      getRect('.category', true).then((rects) => {
        if (isArray(rects)) {
          itemScrollTop.value = rects.map((item) => item.top || 0)
          // scrollTop.value = rects[active.value].top || 0
          // console.log(itemScrollTop,'itemScrollTop')
        }
      })
      // 创建一个选择器查询实例
      const query = uni.createSelectorQuery();
      // 获取 scroll-view 的节点信息
      query.select('.category').boundingClientRect();
      // 获取子元素的节点信息
      query.select('.category').boundingClientRect();
      query.exec((res) => {
        const scrollViewRect = res[0];
        const childElementRect = res[1];
        if (scrollViewRect && childElementRect) {
          // 计算子元素距离 scroll-view 的顶部距离
          const distance = childElementRect.top - scrollViewRect.top;
          // console.log('子元素距离 scroll-view 的顶部距离:', distance);
        }
      });
    })
  })



</script>

<style lang="scss" scoped>
  .page-container {
    box-sizing: border-box;
    .swiper-container {
      padding: 27rpx;
      background: #eeefe7;
      :deep(.custom-image) {
        border-radius: 10rpx;
      }
    }
    .scenic-spot-name-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 27rpx 24rpx 27rpx;
      background: #eeefe7;
      .scenic-spot-name {
        color: #AA5414;
        font-size: 42rpx;
        font-weight: bold;
      }
      .scenic-spot-level {
        font-size: 22rpx;
        border-radius: 7rpx;
        padding: 6rpx 22rpx;
        color: #181818;
        background: #FDFFEB;
      }
    }
    .business-status-container {
      font-size: 25rpx;
      padding:0 27rpx;
      background: #eeefe7;
      .business-status {
        color: #26704E;
      }
      .business-time {
        margin-left: 14rpx;
      }
    }
    .address-contact-container {
      padding:30rpx 27rpx 40rpx 27rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 25rpx;
      background: #eeefe7;
      .address-container {
        flex:1;
      }
      .map-contact-container {
        display: flex;
        align-items: center;
        padding-left: 20rpx;
        .map-container {
          padding-left: 10rpx;
        }
      }
    }
    .notice-container {
      background: #eeefe7;
      padding:0 27rpx 50rpx 27rpx;
      .notice-img {
        width: 28rpx;
        height: 28rpx;
      }
      :deep(.custom-notice-bar) {
        padding: 17rpx 6rpx 17rpx 22rpx;
        border-radius: 10.5rpx;
      }
    }
    .switch-container {
      display: flex;
      align-items: center;
      justify-content: center;
      border-bottom: 1px solid #eeefe7;
      border-radius: 10rpx 10rpx 0 0;
      padding: 22rpx 0 20rpx 0;
      .choice-radio {
        padding: 16rpx 125rpx;
        font-size: 39rpx;
        border-radius: 10rpx;
        overflow: hidden;
      }

      .selected-choice-radio {
        color: #1B9C61;
        background: #EEEFE7;
        font-weight: bold;
      }
    }
	
	.selectedradio {
	  color: #1B9C61;
	  background: #EEEFE7;
	  border: 1rpx solid #1B9C61;
	  font-weight: bold;
	}
    .date-container {
      box-sizing: border-box;
      width: 100%;
      padding: 37.5rpx 0 33.5rpx 28rpx;
    }

    .category-list-container {
      display: flex;
      align-items: center;
      padding: 37.5rpx 0 33.5rpx 28rpx;
      .category-item {
        font-size: 22rpx;
        border-radius: 10rpx;
        font-weight: bold;
        padding: 10rpx 16rpx;
        box-sizing: border-box;
        background: #EEEFE7;
      }
      .category-item:last-child {
        margin-right: 0 !important;
      }
    }

    .around-product-list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      padding: 0 27rpx 200rpx 27rpx;
      background: #eeefe7;
      .around-product-item {
        border-radius: 10rpx;
        overflow: hidden;
        background: #FFFFFF;
        width: 48%;
        .img-container {
          position: relative;
          width: 100%;
          height: 278.5rpx;
          .img {
            width: 100%;
            height: 100%;
            background-size: cover;
          }
          .distant-container {
            position: absolute;
            bottom: 10rpx;
            left: 20rpx;
            display: flex;
            align-items: flex-end;
            font-size: 22rpx;
            color: #FFFFFF;
          }
        }
        .product-name {
          padding: 25rpx 11rpx;
          color: #181818;
          font-size: 30rpx;
          font-weight: bold;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
        .category-item-list {
          padding: 0 11rpx 25rpx 11rpx;
          font-size: 22rpx;
          color: #181818;
		  white-space: nowrap; /* 强制文本不换行 */
		  overflow: hidden; /* 隐藏溢出的内容 */
		  text-overflow: ellipsis; /* 显示省略号 */
        }
      }
    }

    .wraper {
      display: flex;
      height: 100%;
    }

    .content {
      flex: 1;
      padding: 20rpx 30rpx;
      background: #eeefe7;
	  min-height: 2000rpx;
      .category {
        .product-list {
          border-radius: 20rpx;
          background: #ffffff;
          overflow: hidden;
          .product-item {
            padding: 37rpx 25rpx;
            border-bottom: 1rpx solid #EEF0DF;
            .product-name {
              font-size: 29rpx;
              font-weight: bold;
            }
            .product-use-rule {
              font-size: 22rpx;
              padding: 24rpx 0 27rpx 0;
              color: #2B2B24;
            }
            .product-introduction-price-sale-btn {
              align-items: center;
              .product-introduction {
                width:50%;
                font-size: 19.5rpx;
                color: #777777;
              }
              .sale-price {
                flex: 1;
                font-size: 42rpx;
                text-align: center;
                font-weight: bold;
                color: #AA5414;
              }
              .sale-price:before {
                content: "￥";
                font-size: 22rpx;
                font-weight: normal;
              }
              .sale-price:after {
                content: "起";
                font-size: 22rpx;
                font-weight: normal;
              }
              .sale-btn {
                border-radius: 10.5rpx;
                padding: 24rpx 21rpx;
                font-weight: bold;
                color: #FFFFFF;
                background: #AA5414;
              }
            }
          }
        }
      }
    }
  }

</style>
